package top.callback.inf.beautyleaf.segment.dao;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import top.callback.inf.beautyleaf.segment.model.LeafTag;
import top.callback.inf.beautyleaf.common.utils.MybatisHelper;

import java.util.List;

/**
 * 标签 {@link LeafTag} 数据操作工具
 *
 * @author Pengyu Gan
 * CreateDate 2021/3/23
 */
public class LeafTagDao {

    private SqlSessionFactory sqlSessionFactory;

    public LeafTagDao(MybatisHelper helper) {
        sqlSessionFactory = helper.getSqlSessionFactory();
    }

    /**
     * 获取所有的标签信息
     * @return 标签信息列表
     */
    public List<LeafTag> findAll() {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(false)) {
            LeafTagMapper leafTagMapper = sqlSession.getMapper(LeafTagMapper.class);
            return leafTagMapper.findAll();
        }
    }

    /**
     * 获取所有的标签名称
     * @return 标签名称列表
     */
    public List<String> findAllTagNames() {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(false)) {
            LeafTagMapper leafTagMapper = sqlSession.getMapper(LeafTagMapper.class);
            return leafTagMapper.findAllTagNames();
        }
    }

    /**
     * 查询指定名称的标签
     * @param tagName 标签名称
     * @return 标签信息
     */
    public LeafTag findByName(String tagName) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(false)) {
            LeafTagMapper leafTagMapper = sqlSession.getMapper(LeafTagMapper.class);
            return leafTagMapper.findByName(tagName);
        }
    }

    /**
     * 变更指定名称的标签的 maxId
     * @param tagName 标签名称
     */
    public LeafTag updateMaxIdAndGet(String tagName) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
            LeafTagMapper leafTagMapper = sqlSession.getMapper(LeafTagMapper.class);
            leafTagMapper.updateMaxId(tagName);
            return leafTagMapper.findByName(tagName);
        }
    }

    /**
     * 使用指定步长(step)变更指定名称的标签的 maxId
     * @param leafTag 标签信息
     */
    public LeafTag updateMaxIdBySpecificStepAndGet(LeafTag leafTag) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
            LeafTagMapper leafTagMapper = sqlSession.getMapper(LeafTagMapper.class);
            leafTagMapper.updateMaxIdBySpecificStep(leafTag);
            return leafTagMapper.findByName(leafTag.getTagName());
        }
    }
}
